define(function(require,exports,module) {
    var myPub = require('./public');
    var myNavSet = require('./video_nav');
    var myVideoPlay = require('./videoConfig');

    var oWindow = $(window);
    var oWrap = $('.js_wrap');                      // wrap 部分
    var oHeader = $('.js_headerBox');               // 头部
    var oFooter = $('.js_footer');                  // 底部
    var oContain = $('.js_contain');                // 页面内容区域
    var oSideBox = $('.js_sideBox');		        // 侧边按钮框
    var oGoTop = $('.js_goTop');                    // 回到顶部

    var oSildeNav = $('.js_sildeNav ');             // 导航栏
    var oMyCollection = $('.js_myCollection');
    var oMoreBtnBox = $('.js_moreBtnBox');          // 加载动画
    var oLoadingBtn = $('.js_loadingBtn');          // 加载动画
    // 获取产品数据的路径
    var goodsDateUrl = BASE_URL + '/video/getVideoListByMenuId';

    var resizeTimer = null;
    var _ID = null;
    var bLoadOff = true;

	oHeader.on("touchmove",function(e) {e.preventDefault()});
    oFooter.on("touchmove",function(e) {e.preventDefault()});

    // 回到过顶部
    oGoTop.hammer().on('tap',function() {
        oWindow.stop().animate({scrollTop: '0'}, 250);
        myPub.HamstopPropaga();
    });

    module.exports = {
        init: function(data,names) {
            myNavSet.SetVideoNav(data, names);
            sfddjIndex.sfddjInit(true);
            _ID = oSildeNav.find('.swiper-pagination-bullet-active').attr('_ID');
            // 历史数据初始化
            ajaxData.HistoryInit();
            ajaxData.VideoAjaxData(_ID, ajaxData.startData, ajaxData.historyNum, function () {
                ajaxData.HisScrollTop();
            });

            sfddjIndex.ScrollPage();
            // 页面尺寸修改
            oWindow.on('resize',function() {
                if (resizeTimer) {
                    clearTimeout(resizeTimer)
                }
                resizeTimer = setTimeout(function(){
                    sfddjIndex.sfddjInit(true);
                }, 400);
            });
            // 页面跳转记录数据
            oWindow.unload(function(){
                ajaxData.SetSession();
            });
        }
    };

    var ajaxData = {
        sumPage: 0,                 // 总翻页数
        limit: 4,                   // 每次加载多少数据
        pagearr: 1,                 // 翻页数 起始第一页
        startData: 0,               // 加载数据开始位置
        endData: 0,                 // 加载数据结束位置
        dataJson: null,             // 数据存储对象
        pageScroll: 0,              // 滚动高度
        historyNum: 0,              // 历史数据

        // 设置商品数据
        VideoAjaxData: function (_ID, start, limit, fn) {
            var _this = this;
            G_JSON_POST(goodsDateUrl,{
                "limit": limit,
                "start": start,
                ID:_ID
            },function (data) {
                _this.dataJson = data.goodsNew2;

                if( data.status == "success") {

                    _this.sumPage = Math.ceil(data.total/_this.limit);
                    if(_this.sumPage == 0 || (_this.pagearr == _this.sumPage && _this.pagearr > 1 && bLoadOff == false) ) {
                        oMoreBtnBox.show();
                        oLoadingBtn.hide().eq(0).show();
                        return
                    }

                    else {
                        connectHtml.videoInfoHtml(_this.dataJson, function (newVideo) {
                            var oPlayerCenter = newVideo.find(".js_playerCenter");
                            oPlayerCenter.each(function (i) {
                                // console.log('js_videoPlay-' + _ID + '-'+ ajaxData.pagearr + '-' + i)
                                myVideoPlay.videoSet('js_videoPlay-' + _ID + '-'+ ajaxData.pagearr + '-' + i);
                            });
                            sfddjIndex.SetAdsLiScroll();
                        });
                        if(fn)fn();
                        data = null;
                    }

                }
                else {
                    oMoreBtnBox.show();
                    oLoadingBtn.hide().eq(0).show();
                }

            }, function () {
                // start
            }, function () {
                // end
            });
        },

        // 历史数据定位
        HistoryInit : function (fn1, fn2) {
            var _this = this;
            if(sessionStorage.getItem("videoIndex-pageScroll" + _ID) != null) {
                _this.GetSessionData();
                _this.historyNum = _this.pagearr * _this.limit;
                if(fn1) fn1();
            }
            else {
                _this.historyNum = _this.limit;
                if(fn2) fn2();
            }
        },

        // 历史滚动高度
        HisScrollTop: function () {
            if(sessionStorage.getItem("videoIndex-pageScroll" + _ID) != null) {
                var pageScrollNum = sessionStorage.getItem("videoIndex-pageScroll" + _ID);
                oWindow.scrollTop(parseInt(pageScrollNum));
            }
        },

        // 设置历史定位
        SetSession: function () {
            var _this = this;
            sessionStorage.setItem("videoIndex-pagearr" + _ID, _this.pagearr);
            sessionStorage.setItem("videoIndex-pageScroll" + _ID, _this.pageScroll);
        },

        // 记录数据历史数据
        GetSessionData: function() {
            var _this = this;
            if(sessionStorage.getItem("videoIndex-pageScroll" + _ID) != null) {
                var pageNum = sessionStorage.getItem("videoIndex-pagearr" + _ID);
                var pageScrollNum = sessionStorage.getItem("videoIndex-pageScroll" + _ID);
                //设置单个数据页数
                _this.pagearr = parseInt(pageNum);
                //设置页面的数据
                _this.pageScroll = parseInt(pageScrollNum);
            }
        }

    }

    var sfddjIndex = {
        // 页面swiper
        time_Scroll: null,           // 滚动计时器
        // 调整页面位置和初始化
        oSlideAdsScroll : [],
        sfddjInit: function (bOff) {
            // bOff true 执行下面方法
            if(bOff) {
                oContain.css({
                    'padding-top': oHeader.outerHeight(true),
                    'padding-bottom' : oFooter.outerHeight(true),
                });
            }
            oSideBox.stop().animate({'right': '-3.5rem'},300);
            sfddjIndex.SetAdsLiScroll();
        },

        // 设置滚动广告
        SetAdsLiScroll: function () {
            var _this = this;
            var oHScrollBox = $('.js_WScroll');
            oHScrollBox.each(function (i) {
                if(_this.oSlideAdsScroll[i] === undefined) {
                    _this.oSlideAdsScroll[i] = oHScrollBox.eq(i).swiper({
                        freeMode: true,
                        freeModeMomentumRatio: 0.5,
                        lazyLoading: true,
                        watchSlidesProgress: true,
                        watchSlidesVisibility : true,
                        slideClass : 'slide-HScroll',
                        slidesPerView : 'auto',
                        observer: true,
                        observeParents: true,
                        onSlideChangeEnd:function (swiper) {
                            var index = swiper.activeIndex;
                        }
                    });

                }
            });

            // 设置app产品跳转链接
            myPub.JudgeAppHref(oHScrollBox.find('.js_appHref'));
        },

        // 滚动隐藏搜索
        ScrollPage: function () {
            var _this = this;
            var minScrHeight = 200;

            oWindow.on('scroll', function () {
                var afterScroll = $(this).scrollTop();
                // 滚动页面距离底部200像素 延迟150毫秒加载数据
                clearTimeout(_this.time_Scroll);
                _this.time_Scroll = setTimeout(function() {
                    // afterScroll > 300 ? oSideBox.stop().animate({'right':0},150) : oSideBox.stop().animate({'right': '-3.5rem'},150);
                    // 设置缓存记录
                    ajaxData.pageScroll = afterScroll;
                    if(oWrap[0].scrollHeight - afterScroll - oWindow.height() < minScrHeight) {

                        // 设置翻页到最后一页 返回
                        if(ajaxData.pagearr >= ajaxData.sumPage) {
                            bLoadOff = false;
                            ajaxData.dataJson = null;
                            oLoadingBtn.hide().eq(0).show();
                            return;
                        }
                        // 滚动底部页数增加 起始数据等于上次结束数据  新的结束等于页数*页码数
                        ajaxData.startData = ajaxData.limit*ajaxData.pagearr;
                        ajaxData.pagearr++;
                        ajaxData.VideoAjaxData(_ID, ajaxData.startData, ajaxData.limit);
                    }
                },250);
            })

        }
    }

    var connectHtml = {
        videoInfoHtml: function (data,  fn) {
            var shtmlBox = '';

            var _supportAct = '';
            var _collectAct =  '';

            var shtmlTag = '';

            for (var i=0; i<data.length; i++) {
                var video = data[i];
                var labels = video.labelsList;
                if (labels.length > 0) {
                    shtmlTag = '';
                    for (var j= 0;j<labels.length;j++){
                        shtmlTag += '<li>'+labels[j]+'</li>';
                    }
                }

                // 点赞 记录
                if (video.isSupport == true) _supportAct = 'active';

                // 收藏 记录
                if (video.isCollection == true) _collectAct = 'active';

                // 视频列表数据
                shtmlBox +=
                    '<div class="myCollectionCon backWhite js_myCollectionOne">'+
                    '    <div class="collectionConTop"><h2>'+video.videoName+'</h2>'+
                    '        <div class="cancleCollectionBox HBox">'+
                    '            <div class="goodIdeaLeft Bflex1">'+
                    '               <ul>'+
                                        shtmlTag +
                    '               </ul>'+
                    '            </div>'+
                    '            <div class="cancleColRight HBox">' +
                    '               <p class="greatNum js_getGreatNum HBox '+ _supportAct +'" videoId="'+ video.videoId +'">' +
                    '                  <i class="iconStyle icon-goods"></i>' +
                    '                  <span class="verMid js_greatNum allGoodsNum">' + video.supportCount + '</span>' +
                    '               </p>'+
                    '               <p class="rightCancle collectBtn js_collectBtn '+ _collectAct +'" videoId="'+video.videoId+'">'+
                    '                   <span class="collected">'+
                    '                       <i class="iconStyle icon-collect"></i>'+
                    '                       <span class="verMid">收藏</span>'+
                    '                   </span>'+
                    '                   <span class="collected-no">'+
                    '                       <i class="iconStyle icon-collect_act"></i>'+
                    '                       <span class="verMid">已收藏</span>'+
                    '                   </span>'+
                    '               </p>'+
                    '            </div>'+
                    '        </div>'+
                    '    </div>'+
                        connectHtml.videoHtml(video, i) +
                        connectHtml.scrollGoodsHtml(video) +
                    '</div>'
            }

            oMyCollection.append(shtmlBox);
            if(fn)fn($(shtmlBox));
        },

        videoHtml: function (video, index) {
            var videoName = video.videoName;
            // var videoNameTip = '惊天大逆转! 隐藏的实力即将爆发!';
            var bgImg = HTTP_IMAGE_URL + video.videoImgPath;
            var videoSource = video.videoPath;
            var id = video.videoId;
            // console.log('ajaxData.pagearr:' + ajaxData.pagearr)

            var shtml =
                        '<section class="playVideo js_playVideo">'+
                        '    <div class="player-center js_playerCenter">'+
                        '        <video id="js_videoPlay-' + _ID + '-'+ ajaxData.pagearr + '-' + index + '" class="video-js my-video js_my-video" height="100%" width="100%"'+
                        '               controls '+
                        '               preload="none" '+
                        '               playsinline="true" '+
                        '               webkit-playsinline="true" '+
                        '               x-webkit-airplay="allow" '+
                        '               poster="'+ bgImg +'" '+
                        '               videoId="'+id+'" '+
                        '               data-setup="{}"> '+
                        '            <source src="'+ videoSource +'" type="video/mp4">'+
                        '            <source src="'+ videoSource +'" type="video/ogg">'+
                        '            <source src="'+ videoSource +'" type="video/webm">'+
                        '        </video>'+
                        '    </div>'+

                        '    <div class="player-layer js_player-layer" >'+
                        '        <div class="player-video-name">'+
                        '            <h3>'+ videoName +'</h3>'+
                        '        </div>'+
                        // '        <div class="player-video-detail">'+
                        // '            <a href="video-videoDetail.html">'+
                        // '                <span>详情</span><span class="iconStyle icon-chevron-right"></span>'+
                        // '            </a>'+
                        // '        </div>'+
                        '    </div>'+

                        '    <div class="player-repeat js_player-repeat" style="display: none">'+
                        '        <button type="button" class="btnStyle replayBtn js_replayBtn">'+
                        '            <span class="iconStyle icon-redo"></span>'+
                        '            <span>重新播放</span>'+
                        '        </button>'+
                        '    </div>'+
                        '</section>';
            return shtml;

        },

        scrollGoodsHtml: function (data) {
            var goodsList = data.videoGoodsList;
            var shtmlBox = '';
            var shtml = '';

            for (var i=0; i<goodsList.length; i++) {
                var good = goodsList[i];
               shtml +=
                    '<div class="slide-HScroll eachConnectPro leftLineBox">'+
                    '    <a class="eachConnectProduct HBox js_appHref" _href="'+good.goodsSn+'">'+
                    '        <div class="leftProImg">'+
                    '            <figure><img class="swiper-lazy" data-src="'+HTTP_IMAGE_URL+good.image+ smallImgArg200 +'" src="/static_v4/image/loadImg.jpg" alt="">'+
                '</figure>';
                if(good.firstGueeImagePath!=null && good.firstGueeImagePath!=''){
                    shtml += '<img src="'+good.firstGueeImagePath+'"alt="" class="quanpei_video"/>';
                };
                shtml +=  '        </div>'+
                    '        <div class="rightProCon Bflex1 VBox">'+
                    '            <div class="rightProConTop Bflex1">'+
                    '                <h6 class="showOneLine">'+ good.goodsName + '</h6>'+
                    '            </div>'+
                    '            <div class="rightProConBot">'+
                    '                <p><i>￥</i><span>'+good.salePrice+'</span></p>'+
                    '            </div>'+
                    '        </div>'+
                    '    </a>'+
                    '</div>';

            }
            shtmlBox =
                '<div class="connectProducts connectTriangle">'+
                '    <div class="allConnectPro swiper-container js_WScroll">'+
                '        <div class="swiper-wrapper swrap-HScroll HBox">'+
                            shtml +
                '        </div>'+
                '    </div>'+
                '</div>';

            return shtmlBox;

        }
    }
});